<?php
namespace Common\Controller;
use Think\Controller;
use Think\Model;

class BaseController extends Controller{

	protected function _initialize(){
		header("Content-type: text/html; charset=utf-8");
		define('JQ', 'http://apps.bdimg.com/libs/jquery/1.8.2/jquery.min.js');
		define('MAP', 'http://api.map.baidu.com/api?v=2.0&ak=7E10638907487f0b95529028323dc734');
		define('COM', '/Public/Common/');

		define('CSS', '/Public/' . MODULE_NAME . '/css/');
		define('JS', '/Public/' . MODULE_NAME . '/js/');
		define('IMG', '/Public/' . MODULE_NAME . '/images/');
	}

	protected function getList($field, $table, $where, $order = null, $page = false, $listrows = 12, $join = null){
		$table = C('DB_PREFIX') . (is_array($table) ? implode(',' . C('DB_PREFIX'), $table) : $table);
		$model = new Model();
		if($page == true){
			$totalrows = $model->table($table)->where($where)->join($join)->count();
			$page = new \Think\Page($totalrows, $listrows);
			$limit = $page->firstRow . ',' . $page->listRows;
			$this->assign('page', $page->show());
		}
		return $model->table($table)->field($field)->where($where)->order($order)->join($join)->limit($limit)->select();
	}

	protected function getInfo($field, $table, $where, $join = null){
		$table = C('DB_PREFIX') . (is_array($table) ? implode(',' . C('DB_PREFIX'), $table) : $table);
		return M()->table($table)->field($field)->where($where)->join($join)->find();
	}

	protected function updateData($data, $table, $action = 1, $where = ''){
		$model = M($table);
		if($model->create($data, $action)){
			if($action == 1){
				$re = $model->filter('trim')->add();
				//$model->_sql();
				return $re;
			}else{
				if(empty($where)){
					$re = $model->filter('trim')->save();
					return $re;
				}else{
					$re = $model->where($where)->filter('trim')->save();
					return $re;
				}
			}
		}
		return false;
	}

	protected function deleteData($where, $table){
		return M($table)->where($where)->delete();
	}

	protected function returnResult($result, $info = null, $url = null, $params = array()){
		$info = $info ? $info : array('操作成功', '操作失败');
		list($success, $error) = is_array($info) ? $info : array($info, $info);
		if($result === false){
			$data = array('info' => $error, 'status' => 0);
		}else{
			$data = array('info' => $success, 'status' => 1);
		}
		if($url !== false){
			$data['url'] = $url ? $url : U(CONTROLLER_NAME . '/index');
		}
		$this->ajaxReturn(array_merge($data, $params));
	}
}
?>